package com.qwc.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qwc.blog.common.exception.BadRequestException;
import com.qwc.blog.entity.Tag;
import com.qwc.blog.entity.vo.tag.TagListReqDto;
import com.qwc.blog.mapper.TagMapper;
import com.qwc.blog.service.ITagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

import static com.qwc.blog.common.constant.ResponseConstant.USED_NAME;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author qwc
 * @since 2021-10-30
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements ITagService {

    @Override
    public Page<Tag> getTagList(TagListReqDto dto) {
        LambdaQueryWrapper<Tag> wrapper = Wrappers.<Tag>lambdaQuery().like(StringUtils.isNotBlank(dto.getName()), Tag::getName, dto.getName());
        Integer count = baseMapper.selectCount(wrapper);
        return baseMapper.selectPage(PageDTO.of(dto.getPageNum(), dto.getPageSize(), count), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTag(Tag tag, String currentUsername) {
        Tag sameName = baseMapper.selectOne(Wrappers.<Tag>lambdaQuery().eq(Tag::getName, tag.getName()));
        if (Objects.nonNull(sameName)) {
            throw new BadRequestException(USED_NAME);
        }
        tag.setCreateBy(currentUsername);
        baseMapper.insert(tag);
    }
}
